package com.saer.client.grid.admin.permissions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.saer.client.grid.AutoFitListGrid;
import com.saer.client.grid.record.admin.permissions.PermissionRecord;
import com.smartgwt.client.types.DragDataAction;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.MenuItemIfFunction;
import com.smartgwt.client.widgets.menu.events.ClickHandler;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;

public class PermissionsGrid extends AutoFitListGrid {
	
	private boolean userPermissions = false;
	private String userId = null;
	
    public PermissionsGrid(boolean userPermissions) {
    	this.userPermissions = userPermissions;
    	this.setSize("100%", "100%");  
    	this.setCanDragSelectText(false);
    	this.setCanDragRecordsOut(true);  
    	this.setCanAcceptDroppedRecords(true);  
    	this.setDragDataAction(DragDataAction.MOVE);
    	
    	ListGridField permissionNameField = new ListGridField("permissionName", "Permission Name");  
        ListGridField permissionDescField = new ListGridField("permissionDesc", "Permission Description");
        
        this.setFields(permissionNameField, permissionDescField);
        
		Menu contextMenu = new Menu();
		
		if (userPermissions) {
			this.setEmptyMessage("User Permissions");
			
			MenuItem saveMenuItem = new MenuItem("Save Permissions", "icons/16/save.png");
			
			saveMenuItem.addClickHandler(new ClickHandler() {
				public void onClick(MenuItemClickEvent event) {
					//TODO Cameogwt.getRemotewebservice().saveUserAccesses(userId, getUserPermissions(), new SavePermissionsCallBack());
				}
			});
			
			saveMenuItem.setEnableIfCondition(new MenuItemIfFunction() {  
	            public boolean execute(Canvas target, Menu menu, MenuItem item) {  
	                return (userId != null);  
	            }  
	        });  
			
			contextMenu.addItem(saveMenuItem);
		} else {
			this.setEmptyMessage("All Permissions");
		}
		
		this.setContextMenu(contextMenu);
	}
    
    @Override
    public void clearData() {
    	super.clearData();
    	this.userId = null;
    }
    
	public void setData(HashMap<String, String> permissions) {
		ArrayList<PermissionRecord> permissionRecordList = new ArrayList<PermissionRecord>();

		for (Entry<String, String> permission : permissions.entrySet()) {
			permissionRecordList.add(new PermissionRecord(
					permission.getKey(),
					permission.getValue()));
		}

		this.setData(permissionRecordList.toArray(new PermissionRecord[permissionRecordList.size()]));
	}

	private Set<String> getUserPermissions() {
		Set<String> permissionsSet = new HashSet<String>();
		for (ListGridRecord lgr : getRecords()) {
			PermissionRecord pr = (PermissionRecord) lgr;
			permissionsSet.add(pr.getPermissionName());
		}
		return permissionsSet;
	}
	
	public void loadPermissions(String userId) {
		this.userId = userId;
		if (userPermissions) {
			//TODO Cameogwt.getRemotewebservice().getUserAccesses(userId, new LoadPermissionsCallBack());	
		} else {
			//TOD Cameogwt.getRemotewebservice().getAllAccesses(userId, new LoadPermissionsCallBack());	
		}
	}
	
	private class LoadPermissionsCallBack implements AsyncCallback<LinkedHashMap<String, String>> {
		
		public void onSuccess(LinkedHashMap<String, String> result) {
			setData(result);
		}

		public void onFailure(Throwable caught) {
			
		}
	}
	
	private class SavePermissionsCallBack implements AsyncCallback<Void> {
		
		public void onSuccess(Void result) {
			SC.say("User Permissions Save", "Permissions saved successfuly");
			
		}

		public void onFailure(Throwable caught) {
			SC.warn("Failed to save permissions");
		}
	}
    
}
